<template>
  <div class="login-container">
    <div class="login-background-slider">
      <img v-for="(img, index) in backgroundImages" :key="index" :src="img" :class="[
        'login-background-img',
        { active: currentImageIndex === index },
      ]" alt="宠物背景图" />
    </div>
    <div v-if="showAlert" class="custom-alert-overlay" @click.self="closeAlert">
      <div class="custom-alert-box" :class="{ 'alert-success': isSuccessAlert }">
        <div class="alert-icon">
          <component :is="isSuccessAlert ? PawPrintIcon : BoneIcon" size="24" />
        </div>
        <p class="alert-message">{{ alertMessage }}</p>
        <button @click="closeAlert" class="alert-confirm-button">
          {{ isSuccessAlert ? '好的' : '我知道了' }}
        </button>
      </div>
    </div>
    <div class="login-card">
      <div class="login-card-body">
        <div class="login-title-group">
          <h2 class="login-title">{{ isLogin ? "欢迎回来" : "加入我们" }}</h2>
          <p class="login-subtitle">
            {{ isLogin ? "登录以继续您的宠物之旅" : "注册以开始您的宠物之旅" }}
          </p>
        </div>

        <form @submit.prevent="handleSubmit" class="login-form">
          <div class="login-form-group">
            <div v-if="!isLogin" class="login-input-wrapper">
              <input type="text" id="username" v-model="username" required class="login-input" placeholder="用户名" />
              <UserIcon class="login-input-icon" size="20" />
            </div>
            <div v-if="!isLogin" class="login-input-wrapper">
              <input type="text" id="nickname" v-model="nickname" required class="login-input" placeholder="昵称" />
              <UserIcon class="login-input-icon" size="20" />
            </div>
            <div v-if="!isLogin" class="login-input-wrapper">
              <input type="tel" id="phone" v-model="phone" required class="login-input" placeholder="手机号" />
              <PhoneIcon class="login-input-icon" size="20" />
            </div>
            <div v-if="!isLogin" class="login-input-wrapper login-verification-group">
              <input type="text" id="verificationCode" v-model="verificationCode" required
                class="login-verification-input" placeholder="验证码" :readonly="false" />
              <button type="button" @click="sendVerificationCode" class="login-verification-button"
                :disabled="cooldown > 0">
                {{ cooldown > 0 ? `${cooldown}s` : "发送验证码" }}
              </button>
            </div>
            <div v-if="!isLogin" class="login-input-wrapper">
              <input type="password" id="registerPassword" v-model="registerPassword" required class="login-input"
                placeholder="密码" />
              <LockIcon class="login-input-icon" size="20" />
            </div>
            <div v-if="!isLogin" class="login-input-wrapper">
              <input type="password" id="confirmPassword" v-model="confirmPassword" required class="login-input"
                placeholder="确认密码" />
              <LockIcon class="login-input-icon" size="20" />
            </div>
            <div v-if="isLogin" class="login-input-wrapper">
              <input type="text" id="loginUsername" v-model="loginUsername" required class="login-input"
                placeholder="用户名" />
              <UserIcon class="login-input-icon" size="20" />
            </div>
            <div v-if="isLogin" class="login-input-wrapper">
              <input type="password" id="loginPassword" v-model="loginPassword" required class="login-input"
                placeholder="密码" />
              <LockIcon class="login-input-icon" size="20" />
            </div>
            <p v-if="errorMessage" class="login-error-message">
              {{ errorMessage }}
            </p>
            <p v-if="successMessage" class="login-success-message">
              {{ successMessage }}
            </p>
          </div>

          <button type="submit" class="login-submit-button">
            {{ isLogin ? "登录" : "注册" }}
          </button>
        </form>

        <div class="login-toggle-auth">
          <a href="#" @click.prevent="toggleAuthMode" class="login-toggle-auth-link">
            {{ isLogin ? "还没有账号？立即注册" : "已有账号？立即登录" }}
          </a>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import axios from "axios";
import { ref, onMounted, onBeforeUnmount } from "vue";
import { useRouter } from "vue-router";
import Cookies from "js-cookie";
import {
  UserIcon,
  LockIcon,
  PhoneIcon,
  PawPrintIcon,
  BoneIcon,
} from "lucide-vue-next";

const router = useRouter();

const isLogin = ref(true);
const username = ref("");
const nickname = ref("");
const phone = ref("");
const verificationCode = ref("");
const registerPassword = ref("");
const confirmPassword = ref("");
const loginUsername = ref("");
const loginPassword = ref("");
const cooldown = ref(0);
const errorMessage = ref("");
const successMessage = ref(""); // 添加 successMessage 变量
const showAlert = ref(false);
const alertMessage = ref('');
const isSuccessAlert = ref(false);

const generateVerificationCode = () => {
  return Math.floor(100000 + Math.random() * 900000).toString();
};
const toggleAuthMode = () => {
  isLogin.value = !isLogin.value;
  resetForm();
};
const resetForm = () => {
  username.value = "";
  nickname.value = "";
  phone.value = "";
  verificationCode.value = "";
  registerPassword.value = "";
  confirmPassword.value = "";
  errorMessage.value = "";
  successMessage.value = ""; // 重置成功信息
};
const sendVerificationCode = () => {
  if (phone.value.length !== 11) {
    showCustomAlert("请输入正确的手机号码!");
    return;
  }
  if (cooldown.value > 0) return;
  const code = generateVerificationCode();
  showCustomAlert(`您的验证码是：${code}`, true);
  verificationCode.value = code; // 自动填充验证码字段
  cooldown.value = 60;
  const timer = setInterval(() => {
    cooldown.value--;
    if (cooldown.value === 0) {
      clearInterval(timer);
    }
  }, 1000);
};
const accountName = ref(""); // 用户账号
const Avatar = ref(""); // 用户头像URL
const Nickname = ref(""); // 用户昵称
const Password = ref("");
onMounted(() => {
  const storedUser = sessionStorage.getItem("user");
  if (storedUser) {
    const { account, avatar, nickname, password } = JSON.parse(storedUser);
    accountName.value = account;
    Avatar.value = avatar; // 设置头像URL
    Nickname.value = nickname; // 设置昵称
    Password.value = password;
  }
});
const handleSubmit = async () => {
  try {
    if (isLogin.value) {
      const response = await axios.post(
        "http://localhost:8080/Petrescue/users/login",
        {
          account: loginUsername.value,
          password: loginPassword.value,
        },
        {
          withCredentials: true, // 启用 withCredentials
        }
      );
      const { code, data, message } = response.data;

      if (code == 200) {
        // 假设服务器返回了用户信息
        if (data.token && data.user.account) {
          const { id, account, avatar, nickname, password } = data.user;
          accountName.value = account;
          Avatar.value = avatar;
          Nickname.value = nickname;
          Password.value = password; // 假设密码保存在本地，可以忽略
          // 将用户信息保存到sessionStorage
          sessionStorage.setItem(
            "user",
            JSON.stringify({ id, account, avatar, nickname, password })
          );
          // 将token保存到cookie
          Cookies.set("token", data.token, { expires: 7 }); // 设置过期时间为7天
          await router.replace("/home");
        }else{
          errorMessage.value = error.message;
          showCustomAlert("账号密码错误");
        }
      } else {
        errorMessage.value = message;
      }
    } else {
      if (
        !username.value ||
        !phone.value ||
        !verificationCode.value ||
        !registerPassword.value ||
        !confirmPassword.value
      ) {
        throw new Error("所有字段都不能为空");
      }
      if (registerPassword.value !== confirmPassword.value) {
        throw new Error("两次输入的密码不一致");
      }
      if (confirmPassword.value.length < 6) {
        throw new Error("密码至少6位");
      }

      // 注册逻辑
      const res = await axios.post(
        "http://localhost:8080/Petrescue/users/addUser",
        {
          account: username.value,
          password: registerPassword.value,
          nickname: nickname.value,
          phone: phone.value,
        }
      );
      const { code, message } = res.data;
      if (code == 200) {
        showCustomAlert("注册成功，请登录", true);
        isLogin.value = true;
        resetForm();
      } else {
        errorMessage.value = message;
        showCustomAlert("注册失败");
      }
    }
  } catch (error) {
    errorMessage.value = error.message;
    showCustomAlert("账号密码错误");
  }
  
};
// 背景图片数组
const backgroundImages = [
  new URL("../../assets/images/loginImgs/loginImg1.jpeg", import.meta.url).href,
  new URL("../../assets/images/loginImgs/loginImg2.jpeg", import.meta.url).href,
  new URL("../../assets/images/loginImgs/loginImg3.jpeg", import.meta.url).href,
  new URL("../../assets/images/loginImgs/loginImg4.jpeg", import.meta.url).href,
  new URL("../../assets/images/loginImgs/loginImg5.jpeg", import.meta.url).href,
];

const currentImageIndex = ref(0);
let slideInterval;

// 轮播图自动切换
const startSlider = () => {
  slideInterval = setInterval(() => {
    currentImageIndex.value =
      (currentImageIndex.value + 1) % backgroundImages.length;
  }, 5000); // 每5秒切换一次
};

onMounted(() => {
  startSlider();
});

onBeforeUnmount(() => {
  clearInterval(slideInterval);
});

const showCustomAlert = (message, isSuccess = false) => {
  alertMessage.value = message;
  isSuccessAlert.value = isSuccess;
  showAlert.value = true;
};

const closeAlert = () => {
  showAlert.value = false;
};

</script>

<style scoped lang="less">
@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";

.login-container {
  position: relative;
  overflow: hidden;
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 1rem;
  background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);

  .login-background-slider {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 0;

    .login-background-img {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      object-fit: cover;
      opacity: 0;
      transition: opacity 1.5s ease-in-out;
      filter: brightness(0.7);

      &.active {
        opacity: 1;
      }
    }
  }

  .custom-alert-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.4);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
    animation: fadeIn 0.3s ease;

    .custom-alert-box {
      width: 80%;
      max-width: 300px;
      background: #fff9f0;
      border-radius: 12px;
      padding: 1.5rem;
      box-shadow: 0 10px 25px rgba(124, 45, 18, 0.2);
      text-align: center;
      border: 1px solid #f59e0b;
      animation: slideUp 0.3s ease;

      &.alert-success {
        border-color: #65a30d;

        .alert-icon {
          color: #65a30d;
        }

        .alert-confirm-button {
          background: linear-gradient(90deg, #65a30d 0%, #4d7c0f 100%);
        }
      }

      .alert-icon {
        margin-bottom: 1rem;
        color: #dc2626;
      }

      .alert-message {
        color: #7c2d12;
        margin-bottom: 1.5rem;
        font-size: 0.9375rem;
        line-height: 1.5;
      }

      .alert-confirm-button {
        width: 100%;
        padding: 0.75rem;
        background: linear-gradient(90deg, #ea580c 0%, #c2410c 100%);
        color: white;
        border: none;
        border-radius: 8px;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.2s ease;

        &:hover {
          opacity: 0.9;
          transform: translateY(-1px);
        }

        &:active {
          transform: translateY(0);
        }
      }
    }
  }

  @keyframes slideUp {
    from {
      transform: translateY(20px);
      opacity: 0;
    }

    to {
      transform: translateY(0);
      opacity: 1;
    }
  }

  .login-card {
    position: relative;
    z-index: 1;
    width: 100%;
    max-width: 28rem;
    border-radius: 1rem;
    box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1);
    background-color: rgba(255, 251, 240, 0.7);
    /* Warm off-white background */
    border: 1px solid rgba(234, 88, 12, 0.3);
    /* Orange border */
    animation: fadeIn 0.5s ease-out;

    .login-card-body {
      padding: 2rem;

      .login-title-group {
        text-align: center;
        margin-bottom: 2rem;

        .login-title {
          font-size: 1.875rem;
          font-weight: 700;
          color: #7c2d12;
          /* Warm brown text */
        }

        .login-subtitle {
          color: #9a3412;
          /* Slightly lighter brown */
          margin-top: 0.5rem;
          font-size: 0.875rem;
          font-weight: 300;
        }
      }

      .login-form {
        width: 100%;

        .login-form-group {
          display: flex;
          flex-direction: column;
          gap: 1rem;

          .login-input-wrapper {
            position: relative;

            .login-input {
              width: 100%;
              padding: 0.75rem 1rem 0.75rem 2.5rem;
              /* Added left padding for icon */
              color: #7c2d12;
              /* Warm brown text */
              background-color: rgba(254, 243, 199, 0.5);
              /* Light yellow background */
              border-radius: 0.5rem;
              border: 1px solid #f59e0b;
              /* Amber border */
              transition: all 0.3s ease;
              box-shadow: inset 0 1px 3px rgba(251, 191, 36, 0.1);

              &:not(:placeholder-shown) {
                background-color: rgba(254, 243, 199, 0.7);
                border-color: #ea580c;
                /* Orange border */
                box-shadow: inset 0 1px 3px rgba(251, 191, 36, 0.2),
                  0 0 0 1px rgba(234, 88, 12, 0.1);

                ~.login-input-icon {
                  color: #9a3412;
                  /* Darker icon color */
                }
              }

              &:focus {
                outline: none;
                background-color: rgba(254, 243, 199, 0.9);
                border-color: #c2410c;
                /* Dark orange border */
                box-shadow: 0 0 0 2px rgba(234, 88, 12, 0.3),
                  inset 0 1px 3px rgba(251, 191, 36, 0.3);
              }

              &::placeholder {
                color: #d97706;
                /* Amber placeholder */
                opacity: 0.7;
              }
            }

            .login-input-icon {
              position: absolute;
              left: 0.75rem;
              top: 50%;
              transform: translateY(-50%);
              color: #d97706;
              /* Amber icon */
              transition: all 0.3s ease;
            }


          }

          .login-verification-group {
            display: flex;
            gap: 0.5rem; // 添加间距

            .login-verification-input {
              flex: 2;
              padding: 0.75rem 1rem; // 调整内边距
              color: #7c2d12;
              background-color: rgba(254, 243, 199, 0.5);
              border-radius: 0.5rem;
              border: 1px solid #f59e0b;
              transition: all 0.3s ease;
              box-shadow: inset 0 1px 3px rgba(251, 191, 36, 0.1);

              &:focus {
                outline: none;
                background-color: rgba(254, 243, 199, 0.9);
                border-color: #c2410c;
                box-shadow: 0 0 0 2px rgba(234, 88, 12, 0.3),
                  inset 0 1px 3px rgba(251, 191, 36, 0.3);
              }

              &::placeholder {
                color: #d97706;
                opacity: 0.7;
              }
            }

            .login-verification-button {
              flex: 1;
              background-color: #ea580c;
              color: white;
              border: none;
              border-radius: 0.5rem;
              font-weight: 500;
              font-size: 0.875rem;
              transition: all 0.2s ease;
              cursor: pointer;
              white-space: nowrap;

              &:hover {
                background-color: #c2410c;
              }

              &:disabled {
                background-color: #f59e0b;
                cursor: not-allowed;
              }
            }
          }

          .login-error-message {
            color: #b91c1c;
            /* Warm red */
            font-size: 0.75rem;
            margin-top: 0.25rem;
          }

          .login-success-message {
            color: #166534;
            /* Warm green */
            font-size: 0.75rem;
            margin-top: 0.25rem;
          }
        }

        .login-submit-button {
          width: 100%;
          background: linear-gradient(90deg, #ea580c 0%, #c2410c 100%);
          /* Orange gradient */
          color: white;
          font-weight: 500;
          padding: 0.75rem 1rem;
          border-radius: 0.5rem;
          margin-top: 1.5rem;
          border: none;
          transition: all 0.2s ease;
          cursor: pointer;

          &:hover {
            background: linear-gradient(90deg, #c2410c 0%, #9a3412 100%);
            /* Darker orange gradient */
          }
        }
      }

      .login-toggle-auth {
        margin-top: 1.5rem;
        text-align: center;
        font-size: 0.875rem;

        .login-toggle-auth-link {
          color: #ea580c;
          /* Orange link */
          font-weight: 500;
          text-decoration: none;
          transition: all 0.2s ease;

          &:hover {
            color: #9a3412;
            /* Darker orange */
            text-decoration: underline;
          }
        }
      }
    }
  }

  @keyframes fadeIn {
    from {
      opacity: 0;
      transform: translateY(10px);
    }

    to {
      opacity: 1;
      transform: translateY(0);
    }
  }
}

// 装饰元素
.login-decoration-circle-1 {
  position: absolute;
  top: -2.5rem;
  left: -2.5rem;
  width: 5rem;
  height: 5rem;
  border-radius: 50%;
  background-color: #dbeafe;
  opacity: 0.3;
}

.login-decoration-circle-2 {
  position: absolute;
  bottom: -2.5rem;
  right: -2.5rem;
  width: 6rem;
  height: 6rem;
  border-radius: 50%;
  background-color: #e0e7ff;
  opacity: 0.3;
}

// 动画
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>